package com.pubg.information.controller;

import com.pubg.information.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    @Autowired
    LoginService loginService;

    @RequestMapping(value = "/success")
    public String success(){
        return "login";
    }

    @RequestMapping(value = "/login")
    public String loginIndex(){
        return "login";
    }

    @RequestMapping(value = "/login/user")
    public ModelAndView login(@RequestParam("email") String account,
                              @RequestParam("password") String password,
                              Model model,
                              HttpSession session){
        ModelAndView modelAndView = new ModelAndView();
        if (StringUtils.isEmpty(account)||StringUtils.isEmpty(password)){

            modelAndView.setViewName("redirect:/login.html");

            return modelAndView;
        }else {
            if (loginService.login(account,password)){
                String name  = loginService.getNameByAccount(account);

                session.setAttribute("userName",name);
                session.setAttribute("userAccount",account);

                modelAndView.setViewName("redirect:/redic.html");

                return modelAndView;
            }else{
                modelAndView.setViewName("redirect:/login.html");
                return modelAndView;
            }
        }
    }

    @RequestMapping(value = "/register/user")
    public ModelAndView register(@RequestParam("name") String name,
                           @RequestParam("email") String account,
                           @RequestParam("password") String password,
                           Model model,
                           HttpSession session){
        ModelAndView modelAndView = new ModelAndView();
        if (StringUtils.isEmpty(account)||StringUtils.isEmpty(password)||StringUtils.isEmpty(name)){

            modelAndView.setViewName("redirect:/login.html");

            return modelAndView;
        }else{
            loginService.register(account,password,name);

            session.setAttribute("userName",name);
            session.setAttribute("userAccount",account);

            modelAndView.setViewName("redirect:/redic.html");

            return modelAndView;
        }
    }
}
